layui.config({base: '/js/lib/'}).extend({fileupload: 'fileupload'}).use(['layer','form','table','fileupload'], function() {
    var layer = layui.layer, form = layui.form,table = layui.table;
    var id = getUrlParam("id");
    show_loading();
    $('.sel-load').selLoad(function () {
        form.render('select');
        $.get(rurl("/scm/expressStandardQuote/info"),{"id":id},function (res) {
            if(isSuccess(res)) {
                var data = res.data;
                if(data.quote.capped == true) {
                    $("#capped-fee").show();
                } else {
                    $("#capped-fee").hide();
                }
                form.val("quoteForm",data.quote);
                $("#disabled").val(data.quote.disabled);
                $("#capped").val(data.quote.capped);
                var members = data.members || [];
                memberList(members);
            }
        });

    });

    table.on('tool(quote-member-list)', function(obj){
        var data = obj.data;
        if(obj.event === 'deDel'){
            layer.confirm('您确定要删除此行数据？', function(index){
                obj.del();
                memberList(obtainData());
                layer.close(index);
            });
        }
    });
    //监听状态操作
    form.on('switch(capped)', function(obj){
        let checkStatus = obj.elem.checked;
        $("#capped").val(checkStatus);
        if(checkStatus) {
            $("#capped-fee").show();
        } else {
            $("#capped-fee").hide();
            $("#cappedFee").val("");
        }
    });
    form.on('switch(disabled)', function(obj){
        let checkStatus = obj.elem.checked;
        $("#disabled").val(checkStatus);
    });
    $('.save-btn').click(function () {
        if(checkedForm($('.tsf-page-content'))){
            var quote = $('#quoteForm').serializeJson();
            quote['capped'] = $("#capped").val();
            quote['disabled'] = $("#disabled").val();
            var members = obtainData();
            for(let i = 0;i < members.length;i++) {
                let item = members[i];
                if(null == item['endWeight'] || isNaN(parseFloat(item['endWeight']))) {
                    layer.msg('第' + (i + 1) + '行' + '结束重量不能为空且必须为数字');
                    return;
                }
                if(null == item['basePrice'] || isNaN(parseFloat(item['basePrice']))) {
                    layer.msg('第' + (i + 1) + '行' + '基准价不能为空且必须为数字');
                    return;
                }
                if(null == item['price'] || isNaN(parseFloat(item['price']))) {
                    layer.msg('第' + (i + 1) + '行' + '单价不能为空且必须为数字');
                    return;
                }
            }
            show_loading();
            postJSON('scm/expressStandardQuote/edit',{'quote':quote,'members':members},function (res) {
                parent.reloadList();
                closeThisWin('添加成功');
            });
        }
    });

    $("#weight").change(function () {
        let weight = $("#weight").val();
        $("#agencyFee").text("0.00");
        if(null == weight || isNaN(parseFloat(weight))) {
            layer.msg('测算重量不能为空且必须为数字');
            return;
        }
        var members = obtainData();
        for(let i = 0; i < members.length;i++) {
            let item = members[i];
            if(null != item['startWeight'] && !isNaN(parseFloat(item['startWeight']))
                && null != item['endWeight'] && !isNaN(parseFloat(item['endWeight']))
                && null != item['basePrice'] && !isNaN(parseFloat(item['basePrice']))
                && null != item['price'] && !isNaN(parseFloat(item['price']))
                && Number(weight) > Number(item['startWeight']) && Number(weight) <= Number(item['endWeight'])) {
                let totalFee = Math.ceil(Math.round(Number(weight) * 100) / 100) * Number(item['price']) + Number(item['basePrice']);
                $("#agencyFee").text(totalFee);
                break;
            }
        }
    });

});

function memberList(data) {
    layui.table.render({
        elem: '#quote-member-list',limit:1000,id:'quote-member-list',text:{none:'<a href="javascript:" class="def-a" onclick="addRow()"><i class="fa fa-plus-circle"></i>添加一行</a>'}
        ,cols: [[
            {type: 'numbers', title: '序号', width: 50,align:'center',fixed:true}
            ,{field: 'startWeight', title: '开始重量', width: 150,align:'form',templet:'#startWeightTemp'}
            ,{field: 'endWeight', title: '结束重量', width: 150,align:'form',templet:'#endWeightTemp'}
            ,{field: 'basePrice', title: '基准价', width: 150,align:'form',templet:'#basePriceTemp'}
            ,{field: 'price', title: '单价', width: 150,align:'form',templet:'#priceTemp'}
            ,{field: 'oper', title: '操作', width: 65,toolbar: '#deOperaBar',fixed: 'right',align:'center'}
        ]]
        ,data: data
        ,done:function () {

        }
    });
}

function addRow() {
    var data = obtainData();
    var item = {
        id:'',
        startWeight: '',
        endWeight:'',
        basePrice:'',
        price:''
    };
    //起始重量赋初始值
    //当新增第一条时，起始重量为0
    if(data == null || data.length == 0) {
        item['startWeight'] = 0;
    } else {
        //检查如果不是首行则必须填写结束重量，因为下一行的开始重量必须等于上一行的开始重量
        let beforeEndWeight = data[data.length - 1]['endWeight'];
        if(null == beforeEndWeight || isNaN(parseFloat(beforeEndWeight))) {
           layer.msg('结束重量不能为空且必须为数字');
           return;
        }
        item['startWeight'] = data[data.length - 1]['endWeight'];
    }
    data.push(item);
    memberList(data);
}

function obtainData() {
    var data = []
        ,$memberForm = $('#memberForm')
        ,$ids = $memberForm.find('input[name="id"]')
        ,$startWeight = $memberForm.find('input[name="startWeight"]')
        ,$endWeight = $memberForm.find('input[name="endWeight"]')
        ,$basePrice = $memberForm.find('input[name="basePrice"]')
        ,$price = $memberForm.find('input[name="price"]');
    for(var i=0;i<$ids.size();i++){
        var item = {
            startWeight:$($startWeight[i]).val(),
            endWeight:$($endWeight[i]).val(),
            basePrice:$($basePrice[i]).val(),
            price:$($price[i]).val()
        }
        data.push(item);
    }
    return data;
}